<?php
session_start();
require_once 'classes/Database.php';
require_once 'classes/ProductManager.php';
require_once 'classes/OrderManager.php';
require_once 'classes/CDKManager.php';
require_once 'classes/EasyPay.php';

$db = Database::getInstance();
$productManager = new ProductManager();
$orderManager = new OrderManager();
$cdkManager = new CDKManager();
$easyPay = new EasyPay();

// 测试结果数组
$testResults = [];

// 测试1: 数据库连接
try {
    $result = $db->query("SELECT 1 as test", []);
    if (!empty($result) && $result[0]['test'] == 1) {
        $testResults['database'] = ['status' => 'success', 'message' => '数据库连接正常'];
    } else {
        $testResults['database'] = ['status' => 'error', 'message' => '数据库连接异常'];
    }
} catch (Exception $e) {
    $testResults['database'] = ['status' => 'error', 'message' => '数据库连接失败: ' . $e->getMessage()];
}

// 测试2: 商品管理
try {
    $products = $productManager->getAllProducts();
    if (is_array($products)) {
        $testResults['products'] = ['status' => 'success', 'message' => '商品管理正常，共 ' . count($products) . ' 个商品'];
    } else {
        $testResults['products'] = ['status' => 'error', 'message' => '商品管理异常'];
    }
} catch (Exception $e) {
    $testResults['products'] = ['status' => 'error', 'message' => '商品管理失败: ' . $e->getMessage()];
}

// 测试3: CDK管理
try {
    $cdks = $cdkManager->getAllCDKs();
    if (is_array($cdks)) {
        $testResults['cdks'] = ['status' => 'success', 'message' => 'CDK管理正常，共 ' . count($cdks) . ' 个CDK'];
    } else {
        $testResults['cdks'] = ['status' => 'error', 'message' => 'CDK管理异常'];
    }
} catch (Exception $e) {
    $testResults['cdks'] = ['status' => 'error', 'message' => 'CDK管理失败: ' . $e->getMessage()];
}

// 测试4: 订单管理
try {
    $orders = $orderManager->getAllOrders();
    if (is_array($orders)) {
        $testResults['orders'] = ['status' => 'success', 'message' => '订单管理正常，共 ' . count($orders) . ' 个订单'];
    } else {
        $testResults['orders'] = ['status' => 'error', 'message' => '订单管理异常'];
    }
} catch (Exception $e) {
    $testResults['orders'] = ['status' => 'error', 'message' => '订单管理失败: ' . $e->getMessage()];
}

// 测试5: 支付类
try {
    $testOrderNo = 'TEST' . time();
    $testAmount = 1.00;
    $testProductId = 1;
    
    // 测试创建订单
    $orderId = $orderManager->createOrder($testOrderNo, $testProductId, $testAmount, 'test@example.com');
    if ($orderId) {
        $testResults['order_create'] = ['status' => 'success', 'message' => '订单创建正常，订单ID: ' . $orderId];
        
        // 测试分配CDK
        $cdk = $cdkManager->assignCDK($orderId);
        if ($cdk) {
            $testResults['cdk_assign'] = ['status' => 'success', 'message' => 'CDK分配正常，CDK: ' . $cdk];
        } else {
            $testResults['cdk_assign'] = ['status' => 'warning', 'message' => 'CDK分配失败（可能无可用CDK）'];
        }
        
        // 清理测试订单
        $db->query("DELETE FROM orders WHERE order_no = ?", [$testOrderNo]);
    } else {
        $testResults['order_create'] = ['status' => 'error', 'message' => '订单创建失败'];
    }
} catch (Exception $e) {
    $testResults['order_create'] = ['status' => 'error', 'message' => '订单创建异常: ' . $e->getMessage()];
}

// 测试6: 文件权限检查
$filesToCheck = [
    'config/database.php' => '配置文件',
    'classes/Database.php' => '数据库类',
    'classes/ProductManager.php' => '商品管理类',
    'classes/OrderManager.php' => '订单管理类',
    'classes/CDKManager.php' => 'CDK管理类',
    'classes/EasyPay.php' => '支付类'
];

foreach ($filesToCheck as $file => $description) {
    if (file_exists($file)) {
        if (is_readable($file)) {
            $testResults['file_' . str_replace('/', '_', $file)] = [
                'status' => 'success', 
                'message' => $description . ' 文件可读'
            ];
        } else {
            $testResults['file_' . str_replace('/', '_', $file)] = [
                'status' => 'error', 
                'message' => $description . ' 文件不可读'
            ];
        }
    } else {
        $testResults['file_' . str_replace('/', '_', $file)] = [
            'status' => 'error', 
            'message' => $description . ' 文件不存在'
        ];
    }
}

// 统计测试结果
$totalTests = count($testResults);
$successTests = 0;
$warningTests = 0;
$errorTests = 0;

foreach ($testResults as $test) {
    if ($test['status'] === 'success') $successTests++;
    if ($test['status'] === 'warning') $warningTests++;
    if ($test['status'] === 'error') $errorTests++;
}

$overallStatus = ($errorTests === 0) ? 'success' : (($warningTests > 0) ? 'warning' : 'error');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统测试 - CDK支付系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .test-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px 0;
            text-align: center;
        }
        .test-card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .status-badge {
            font-size: 0.9em;
            padding: 6px 12px;
        }
        .summary-card {
            border: none;
            border-radius: 15px;
            padding: 30px;
            text-align: center;
            margin-bottom: 30px;
        }
        .summary-success {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
            color: white;
        }
        .summary-warning {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
            color: white;
        }
        .summary-error {
            background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
            color: white;
        }
    </style>
</head>
<body>
    <!-- 头部 -->
    <div class="test-header">
        <div class="container">
            <h1 class="display-4 fw-bold mb-3">
                <i class="fas fa-cogs me-2"></i>系统测试
            </h1>
            <p class="lead">CDK支付系统功能完整性测试</p>
        </div>
    </div>

    <div class="container py-5">
        <!-- 测试摘要 -->
        <div class="row justify-content-center mb-5">
            <div class="col-md-8">
                <div class="summary-card <?php echo 'summary-' . $overallStatus; ?>">
                    <h2 class="mb-3">测试摘要</h2>
                    <div class="row">
                        <div class="col-md-3">
                            <h3><?php echo $totalTests; ?></h3>
                            <p>总测试项</p>
                        </div>
                        <div class="col-md-3">
                            <h3><?php echo $successTests; ?></h3>
                            <p>成功</p>
                        </div>
                        <div class="col-md-3">
                            <h3><?php echo $warningTests; ?></h3>
                            <p>警告</p>
                        </div>
                        <div class="col-md-3">
                            <h3><?php echo $errorTests; ?></h3>
                            <p>错误</p>
                        </div>
                    </div>
                    <div class="mt-4">
                        <?php if ($overallStatus === 'success'): ?>
                            <span class="badge bg-success status-badge fs-6">
                                <i class="fas fa-check-circle me-1"></i> 系统运行正常
                            </span>
                        <?php elseif ($overallStatus === 'warning'): ?>
                            <span class="badge bg-warning status-badge fs-6">
                                <i class="fas fa-exclamation-triangle me-1"></i> 系统存在警告
                            </span>
                        <?php else: ?>
                            <span class="badge bg-danger status-badge fs-6">
                                <i class="fas fa-times-circle me-1"></i> 系统存在错误
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- 测试结果详情 -->
        <div class="row">
            <div class="col-12">
                <h3 class="mb-4">详细测试结果</h3>
                <?php foreach ($testResults as $testName => $result): ?>
                    <div class="card test-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h5 class="card-title mb-1"><?php echo ucfirst(str_replace('_', ' ', $testName)); ?></h5>
                                    <p class="card-text text-muted mb-0"><?php echo $result['message']; ?></p>
                                </div>
                                <div>
                                    <?php if ($result['status'] === 'success'): ?>
                                        <span class="badge bg-success status-badge">
                                            <i class="fas fa-check me-1"></i> 成功
                                        </span>
                                    <?php elseif ($result['status'] === 'warning'): ?>
                                        <span class="badge bg-warning status-badge">
                                            <i class="fas fa-exclamation-triangle me-1"></i> 警告
                                        </span>
                                    <?php else: ?>
                                        <span class="badge bg-danger status-badge">
                                            <i class="fas fa-times me-1"></i> 错误
                                        </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="row mt-5">
            <div class="col-12 text-center">
                <div class="d-grid gap-2 d-md-block">
                    <a href="demo.php" class="btn btn-primary btn-lg me-md-2">
                        <i class="fas fa-eye me-2"></i>查看演示页面
                    </a>
                    <a href="admin/login.php" class="btn btn-outline-primary btn-lg me-md-2">
                        <i class="fas fa-user-shield me-2"></i>后台管理
                    </a>
                    <a href="index.php" class="btn btn-success btn-lg">
                        <i class="fas fa-shopping-cart me-2"></i>开始购买
                    </a>
                </div>
            </div>
        </div>

        <!-- 系统信息 -->
        <div class="row mt-5">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-info-circle me-2"></i>系统信息
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-sm">
                                    <tr>
                                        <td><strong>PHP版本:</strong></td>
                                        <td><?php echo PHP_VERSION; ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>服务器软件:</strong></td>
                                        <td><?php echo $_SERVER['SERVER_SOFTWARE'] ?? '未知'; ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>最大执行时间:</strong></td>
                                        <td><?php echo ini_get('max_execution_time'); ?> 秒</td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-sm">
                                    <tr>
                                        <td><strong>内存限制:</strong></td>
                                        <td><?php echo ini_get('memory_limit'); ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>上传文件大小:</strong></td>
                                        <td><?php echo ini_get('upload_max_filesize'); ?></td>
                                    </tr>
                                    <tr>
                                        <td><strong>当前时间:</strong></td>
                                        <td><?php echo date('Y-m-d H:i:s'); ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
